package com.ruoyi.worker.service.impl;

import com.google.common.collect.Lists;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.worker.domain.CycleSchedule;
import com.ruoyi.worker.domain.TermSchedule;
import com.ruoyi.worker.domain.UserSchedule;
import com.ruoyi.worker.mapper.TermScheduleMapper;
import com.ruoyi.worker.service.TermScheduleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName: TermScheduleServiceImpl
 * @Description:
 * @Author: 刘松山
 * @Date: 2021/10/14 20:31
 */
@Service
public class TermScheduleServiceImpl implements TermScheduleService {

    @Autowired
    private TermScheduleMapper termScheduleMapper;

    @Override
    public List<TermSchedule> listTermSchedule(TermSchedule t) {
        return termScheduleMapper.listTermSchedule(t);
    }

    @Override
    @Transactional
    public int addTermSchedule(TermSchedule t) {
        int flag = 0;
        try {
            List<String> dateList = DateUtils.findDates(t.getBeginTime(), t.getEndTime());
            String[] tableDataRow = t.getTableData().split(";");
            List<UserSchedule> list = new ArrayList<>();
            t.setUserNum(tableDataRow.length);
              flag = termScheduleMapper.addTermSchedule(t);
            //长期工具体排班记录保存

            for (int i = 0; i < tableDataRow.length; i++) {

                String[] tableDataColumn = tableDataRow[i].split(",");
                for (int k = 5; k < tableDataColumn.length; k++) {
                    UserSchedule userSchedule = new UserSchedule();
                    userSchedule.setParentId(t.getId());
                    userSchedule.setCreateBy(t.getCreateBy());
                    userSchedule.setUserId(Long.parseLong(tableDataColumn[0]));
                    userSchedule.setUserName(tableDataColumn[1]);
                    String postId =tableDataColumn[2].replaceAll(" ","");
                    if("".equals(postId)){
                        userSchedule.setPostId(0l);
                    }else{
                        userSchedule.setPostId(Long.parseLong(tableDataColumn[2]));
                    }
                    userSchedule.setPostName(tableDataColumn[3]);
                    userSchedule.setIdCard(tableDataColumn[4]);
                    userSchedule.setTermTimeShifName(tableDataColumn[k]);
                    userSchedule.setDateTime(dateList.get(k - 5));
                    list.add(userSchedule);
                }
            }

            flag = termScheduleMapper.addUserSchedule(list);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return flag;
    }

    @Override
    @Transactional
    public int modifyTermSchedule(TermSchedule t) {
        int flag = 0;
        Long[] ids = new Long[1];
        ids[0] = t.getId();
        //删除长期工记录排班记录
        termScheduleMapper.delUserSchedule(ids);
        //长期工具体排班记录保存
        try {
            List<String> dateList = DateUtils.findDates(t.getBeginTime(), t.getEndTime());
            String[] tableDataRow = t.getTableData().split(";");
            List<UserSchedule> list = new ArrayList<>();

           flag =  termScheduleMapper.modifyTermSchedule(t);

            for (int i = 0; i < tableDataRow.length; i++) {

                String[] tableDataColumn = tableDataRow[i].split(",");
                for (int k = 5; k < tableDataColumn.length; k++) {
                    UserSchedule userSchedule = new UserSchedule();
                    userSchedule.setParentId(t.getId());
                    userSchedule.setCreateBy(t.getCreateBy());
                    userSchedule.setUserId(Long.parseLong(tableDataColumn[0]));
                    userSchedule.setUserName(tableDataColumn[1]);
                    if("".equals(tableDataColumn[2]) || " ".equals(tableDataColumn[2])){
                        userSchedule.setPostId( 0);
                    }else{
                        userSchedule.setPostId( Long.parseLong(tableDataColumn[2]));
                    }

                    userSchedule.setPostName(tableDataColumn[3]);
                    userSchedule.setIdCard(tableDataColumn[4]);
                    userSchedule.setTermTimeShifName(tableDataColumn[k]);
                    userSchedule.setDateTime(dateList.get(k - 5));
                    list.add(userSchedule);
                }
            }

            flag = termScheduleMapper.addUserSchedule(list);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return flag;
    }

    @Override
    public int modifyTermScheduleStatus(TermSchedule t) {
        int flag = termScheduleMapper.modifyTermSchedule(t);
        return flag;
    }

    @Override
    @Transactional
    public int delBacthTermSchedule(Long[] ids) {
        int flag = termScheduleMapper.delBacthTermSchedule(ids);
        //删除排班表下的长期工排班记录
        flag = termScheduleMapper.delUserSchedule(ids);
        return flag;
    }

    @Override
    public TermSchedule getTermSchedule(long id) {
        TermSchedule t = termScheduleMapper.getTermSchedule(id);
        //获取排班表下的长期工排班记录
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("groupId", t.getGroupId());
        List<Map<String, Object>> userScheduleList =  termScheduleMapper.listUserSchedule(param);
        List<UserSchedule> list = termScheduleMapper.listUserScheduleResult(param);
        List<Map<String, Object>> tableDataList = new ArrayList<>();
        List<Map<String, Object>> tableTitleDataList = new ArrayList<>();

        List<List<UserSchedule>> userOfList = Lists.newArrayList();
        list.stream().collect(Collectors.groupingBy(UserSchedule::getUserId, Collectors.toList()))
                .forEach((userId, userList) -> {
                    userOfList.add(userList);
                });
        //如果在编辑时 考勤组多出新用户 默认排班为空
        tableDataList =this.getNewUserSchedul(userOfList,userScheduleList,tableDataList);
        for (List<UserSchedule> l : userOfList) {
            Map<String, Object> map = new HashMap<>();
            map.put("userId", l.get(0).getUserId());
            map.put("userName", l.get(0).getUserName());
            map.put("postId", l.get(0).getPostId());
            map.put("postName", l.get(0).getPostName());
            map.put("idCard", l.get(0).getIdCard());
            for (UserSchedule u : l) {
                map.put(u.getDateTime(), u.getTermTimeShifName());
            }
            tableDataList.add(map);
        }
        t.setTableDataList(tableDataList);
        List<String> dataList = null;
        try {
            dataList = DateUtils.findDates(t.getBeginTime(), t.getEndTime());

            for (int i=0;i<dataList.size();i++ ) {
                Map<String, Object> map = new HashMap<>();
                map.put("value", dataList.get(i));
                map.put("lable",  dataList.get(i));
                tableTitleDataList.add(map);
            }
            t.setTableTitleDataList(tableTitleDataList);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return t;
    }


    public List<Map<String, Object>> getNewUserSchedul(  List<List<UserSchedule>> userOfList ,List<Map<String, Object>> list,List<Map<String, Object>> resultList){
        //如果在编辑时 考勤组多出新用户 默认排班为空
        if(list.size() >userOfList.size()){
            for (Map<String, Object> m : list) {
                long userId =Long.parseLong(m.get("userId")+"") ;
                int flag =0;
                for (List<UserSchedule> l : userOfList) {
                    for (UserSchedule u : l) {
                        m.put(u.getDateTime(), "");
                    }
                    if(userId==l.get(0).getUserId()){
                        flag =1;
                        break;
                    }
                }
                if(flag==0){
                    resultList.add(m);
                }
            }
        }
        return resultList;
    }

    @Override
    public List<CycleSchedule> listCycleSchedule() {
        return termScheduleMapper.listCycleSchedule();
    }

    @Override
    public List<Map<String, Object>> listUserSchedule(Map<String, Object> param) {
        List<String> dataList = null;
        List<Map<String, Object>> list =  termScheduleMapper.listUserSchedule(param);
        List<Map<String, Object>> resultList = new ArrayList<>();

        try {

            dataList = DateUtils.findDates(param.get("beginTime") + "", param.get("endTime") + "");
            if (param.get("id") == null || "".equals(param.get("id")+"") ) {
                for (Map<String, Object> map : list) {
                    for (String s : dataList) {
                        map.put(s, "");

                    }
                }
            } else {
                List<UserSchedule> userlist = termScheduleMapper.listUserScheduleResult(param);

                List<List<UserSchedule>> userOfList = Lists.newArrayList();
                userlist.stream().collect(Collectors.groupingBy(UserSchedule::getUserId, Collectors.toList()))
                        .forEach((userId, userList) -> {
                            userOfList.add(userList);
                        });

                //如果在编辑时 考勤组多出新用户 默认排班为空
                resultList =this.getNewUserSchedul(userOfList,list,resultList);

                for (List<UserSchedule> l : userOfList) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("userId", l.get(0).getUserId());
                    map.put("userName", l.get(0).getUserName());
                    map.put("postId", l.get(0).getPostId());
                    map.put("postName", l.get(0).getPostName());
                    map.put("idCard", l.get(0).getIdCard());
                    for (UserSchedule u : l) {
                        map.put(u.getDateTime(), u.getTermTimeShifName());
                    }
                    resultList.add(map);
                }
                list.clear();
                list=resultList;
            }


        } catch (ParseException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> listUserScheduleList(Map<String, Object> param) {
        return this.termScheduleMapper.listUserSchedule(param);
    }

    @Override
    @Transactional
    public int addCycleSchedule(List<CycleSchedule> list) {
        //先删除后保存
        termScheduleMapper.delCycleSchedule();
        termScheduleMapper.addCycleSchedule(list);
        return 1;
    }

    @Override
    public List<UserSchedule> listuserDateSchedule(TermSchedule t) {
        List<String> dateList = null;
        try {
            dateList = DateUtils.findDates(t.getBeginTime(), t.getEndTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String[] tableDataRow = t.getTableData().split(";");
        List<UserSchedule> list = new ArrayList<>();
        //查询校验当日是否已经排班了
        List<Long> userList = new ArrayList<>();
        for (int i = 0; i < tableDataRow.length; i++) {

            String[] tableDataColumn = tableDataRow[i].split(",");
            for (int k = 5; k < tableDataColumn.length; k++) {
                userList.add(Long.parseLong(tableDataColumn[0]));
            }
        }

        Map<String,Object> paraMap = new HashMap<>();
        paraMap.put("userList",userList);
        paraMap.put("dateList",dateList);
        List<UserSchedule> userDateScheduleList =termScheduleMapper.listuserDateSchedule(paraMap);

        return userDateScheduleList;
    }
}
